import cloud from '@lafjs/cloud'
let data
let dbName = "admin-teaching-schedule"
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  switch (ctx.body.type) {
    case "add":
      return await addClass()
      break;
    case "list":
      return await list()
      break;
    case "del":
      return await delFunc()
      break;
    case "details":
      return await details()
      break;
    case "update":
      return await update()
      break;
    case "query":
      return await query()
      break;
    case "all":
      return await all()
      break;
    case "lessonHours"://已授课时
      return lessonHours()
      break;
    case "queryLessonNum"://排期节数
      return queryLessonNum()
      break;
    default:
      break;
  }
}

//已授课时
async function lessonHours() {
  let obj = {
    signInComplete: 1,
    classId: data.classId,
  }
  let res = await db.collection(dbName).find(obj).toArray()
  return cloud.utils.requestReturn({ data: res })
}

//全部课程
async function all() {
  let query = cloud.utils.fuzzyQuery({ ...data })
  delete query.curriculumId
  if (data.curriculumId && data.curriculumId.length) {
    query.curriculumId = { $in: data.curriculumId }
  }
  console.log("查询入参", query)
  let aa = await db.collection(dbName).find(query).toArray()
  return cloud.utils.requestReturn({ data: aa })
}

//查询排期节数（是第几节课）
async function queryLessonNum() {
  let aa = await db.collection(dbName)
    .find({ classId: data.classId })
    .sort({ sort: 1, dateStamp: 1 })
    .toArray()
  let index = cloud.utils.findIndexByField(aa, "_id", data._id)
  return cloud.utils.requestReturn({ data: index + 1 })
}


async function query() {
  let aa = await db.collection(dbName)
    .find({ classId: data.classId })
    .sort({ sort: 1, dateStamp: 1 })
    .toArray()
  return cloud.utils.requestReturn({ data: aa })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: data._id },
    dataJson: query
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function addClass() {
  let aa = await db.collection(dbName)
    .find({ classId: data.classId, date: data.date })
    .toArray()
  for (let index = 0; index < aa.length; index++) {
    const element = aa[index];
    if (isTimeRangeOverlap(element.classStartTime, element.classEndTime, data.classStartTime, data.classEndTime)) {
      return cloud.utils.requestReturn({ msg: `${data.date} ${data.classStartTime}-${data.classEndTime}时间段与${element.classStartTime}-${element.classEndTime}时间段冲突`, code: 500 })
    }
  }

  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: false
  });

  //判断之前是否有这一天
  function isTimeRangeOverlap(startTime1, endTime1, startTime2, endTime2) {
    // 将时间字符串转换为分钟数
    const convertToMinutes = (timeStr) => {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    };

    const startMinutes1 = convertToMinutes(startTime1);
    const endMinutes1 = convertToMinutes(endTime1);
    const startMinutes2 = convertToMinutes(startTime2);
    const endMinutes2 = convertToMinutes(endTime2);

    return !(endMinutes1 < startMinutes2 || startMinutes1 > endMinutes2);
  }
  return cloud.utils.requestReturn({ data: "" })
}

//排期详情
async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName: "admin-teaching-schedule",
    whereJson: { _id: data.scheduleId },
  });
  if (!res) return cloud.utils.requestReturn({ msg: "没有找到该排课信息", code: 500 })
  let { curriculumId, classId } = res  //排期详情
  let rew = await cloud.nw.db.findByWhereJson({
    dbName: "web-course",
    whereJson: { _id: curriculumId },
  });
  if (rew && rew.name) res["curriculumnName"] = rew.name
  let { className, classAddress, classTeacherId, classNum } = await cloud.nw.db.findByWhereJson({
    dbName: "admin-class",
    whereJson: { _id: classId },
  });
  res["className"] = className
  res["classAddress"] = classAddress
  res["classNum"] = classNum
  let studentCount = await cloud.nw.db.count({
    dbName: "admin-class-student",
    whereJson: { classId }
  });
  res["studentCount"] = studentCount  //实际学生数量
  let { userName } = await cloud.nw.db.findByWhereJson({
    dbName: "admin-users",
    whereJson: { _id: classTeacherId },
  });
  res["classTeacherName"] = userName  //实际学生数量
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function list() {
  let query = cloud.utils.fuzzyQuery(data)
  delete query.pageIndex
  delete query.pageSize
  query = cloud.utils.extractValidKeys({ ...query })

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson: query,
    sortArr: [{ "name": "_add_time", "type": "desc" }],
    // 副表列表
    foreignDB: [
      {
        dbName: "web-course",//副表 order
        localKey: "curriculumId",
        foreignKey: "_id",
        as: "course_Info",
        limit: 1,
        // 副表 where 条件
        whereJson: {},
        // 副表字段显示规则
        fieldJson: {
          "name": 1
        },
      },
      {
        dbName: "admin-users",//副表 order
        localKey: "classTeacherId",
        foreignKey: "_id",
        as: "classTeacher_Info",
        limit: 1,
        // 副表 where 条件
        whereJson: {},
        // 副表字段显示规则
        fieldJson: {
          "userName": 1
        },
      },
    ]
  });

  return cloud.utils.requestReturn({ data: res })
}
